package com.quectel.cms.controller.car;


import cn.hutool.core.util.DesensitizedUtil;
import com.quectel.business.common.util.sys.SysCodeUtils;
import com.quectel.cms.controller.BaseController;
import com.quectel.cms.interceptor.LoginUserSession;
import com.quectel.cms.util.SessionHolder;
import com.quectel.constant.global.SystemConstants;
import com.quectel.util.aspect.log.annotation.Log;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.constant.sys.SysCodeKeyConstants;
import com.quectel.core.module.car.dto.CarDto;
import com.quectel.core.module.car.service.CarService;
import com.quectel.core.module.household.dto.HouseholdDto;
import com.quectel.core.module.household.service.HouseholdService;
import com.quectel.core.module.village.dto.VillageBuildingDto;
import com.quectel.core.module.village.dto.VillageDto;
import com.quectel.core.module.village.service.VillageBuildingService;
import com.quectel.core.module.village.service.VillageRoomService;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.util.common.POIUtils;
import com.quectel.util.common.Page;
import com.quectel.util.common.Request;
import com.quectel.util.common.Response;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author caolu
 * @email louis.cao@quectel.com
 * @date 2021-11-09 14:20:06
 */
@RestController
@RequestMapping("car")
@Tag(name = "CarController", description = "车辆相关api")
public class CarController extends BaseController {

    @DubboReference
    private CarService carService;
    @DubboReference
    private VillageService villageService;
    @DubboReference
    private HouseholdService householdService;
    @DubboReference
    private VillageBuildingService villageBuildingService;
    @DubboReference
    private VillageRoomService villageRoomService;


    /**
     * 列表
     */
    @PostMapping("importExcel")
    @RequirePermissions(values = "car:importExcel")
    @Operation(summary = "导入车辆信息")
    @Log(express = "导入车辆信息")
    public Response<Object> importExcel(
            MultipartHttpServletRequest request
    ) {
        LoginUserSession sysUser = SessionHolder.getSysUser();
        Date now = new Date();
        List<CarDto> list = new ArrayList<>();
        Iterator<String> fileNames = request.getFileNames();
        while (fileNames.hasNext()) {
            String next = fileNames.next();
            List<MultipartFile> files = request.getFiles(next);
            for (MultipartFile file : files) {
                try {
                    //校验楼栋数据合法性
                    List<Map<Integer, String>> analysis = POIUtils.analysis(file.getInputStream(), 1, 0);
                    for (Map<Integer, String> map : analysis) {
                        try {
                            VillageDto villageDto = villageService.selectByName(sysUser.getTenantId(), map.get(0));
                            if (villageDto == null || !Objects.equals(villageDto.getTenantId(), SessionHolder.getSysUser().getTenantId())) {
                                continue;
                            }

                            CarDto dto = new CarDto();
                            dto.setVillageId(villageDto.getId());
                            dto.setLicense(map.get(1));
                            dto.setLicenseColor(SysCodeUtils.easyToGetValue(SysCodeKeyConstants.LICENSE_COLOR, map.get(2), Byte.class));
                            dto.setCarType(SysCodeUtils.easyToGetValue(SysCodeKeyConstants.CAR_TYPE, map.get(3), Byte.class));
                            dto.setOwnerName(map.get(4));
                            dto.setOwnerMobile(map.get(5));
                            dto.setCreateTime(now);

                            Long buildingDtoId = null;
                            String villageBuildingName = map.get(6);
                            String roomName = map.get(8);
                            if (StringUtils.isNotEmpty(villageBuildingName) && StringUtils.isNotEmpty(roomName)) {
                                VillageBuildingDto villageBuildingDto = villageBuildingService.selectByName(villageDto.getId(), villageBuildingName);
                                if (villageBuildingDto != null) {
                                    buildingDtoId = villageBuildingDto.getId();
                                }
                                if (!roomName.contains("室")) {
                                    roomName = map.get(8) + "室";
                                }
                            }

                            dto.setBrandModel(map.get(9));
                            dto.setVehicleIdNo(map.get(10));
                            dto.setEngineNo(map.get(11));

                            if (StringUtils.isBlank(dto.getLicense())) {
                                continue;
                            }

                            fillSaveCommonData(dto);
                            list.add(dto);
                        } catch (Exception e) {
                            continue;
                        }
                    }
                } catch (Exception e) {
                    logger.error("解析楼栋信息出错");
                }
            }
        }
        int successCount = 0;
        for (CarDto carDto : list) {
            try {
                successCount++;
                CarDto dbValue = carService.selectOne(carDto.getVillageId(), carDto.getLicense(), carDto.getLicenseColor());
                if (dbValue != null) {
                    continue;
                }
                carService.save(carDto);
            } catch (Exception e) {
                logger.error("导入失败", e);
                continue;
            }
        }
        return Response.error("导入成功,导入成功数量为:" + successCount);
    }

    /**
     * 列表
     */
    @GetMapping("exportExcel")
    @RequirePermissions(values = "car:exportExcel")
    @Operation(summary = "导出车辆信息")
    @Log(express = "导出车辆信息")
    public void exportExcel(@RequestParam Map<String, Object> params, HttpServletResponse hresp) {
        Request request = Request.configParamsNotPage(params);

        super.fillAuthorityData(params);

        List<CarDto> result = new ArrayList<>();
        int pageNo = 0;
        params.put("limit", 1000);
        while (true) {
            params.put("offset", pageNo++ * 1000);
            List<CarDto> list = carService.queryList(params);
            if (org.apache.commons.collections4.CollectionUtils.isEmpty(list)) {
                break;
            }
            result.addAll(list);
            if (list.size() < 1000) {
                break;
            }
        }
        String[] headers = new String[]{"所属小区", "车牌号", "车辆颜色", "车辆类型", "所属人姓名", "所属人电话"};
        List<String[]> dataList = new ArrayList<>();
        for (CarDto data : result) {
            String[] item = new String[headers.length];
            item[0] = data.getVillageName();
            item[1] = DesensitizedUtil.carLicense(data.getLicense());
            item[2] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.LICENSE_COLOR, data.getLicenseColor() + "");
            item[3] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.CAR_TYPE, data.getCarType() + "");
            item[4] = DesensitizedUtil.chineseName(data.getOwnerName()) + "";
            item[5] = DesensitizedUtil.mobilePhone(data.getOwnerMobile()) + "";
            dataList.add(item);
        }
        POIUtils.exportExcel(hresp, "车辆信息", headers, dataList, "车辆信息");

    }

    /**
     * 列表
     */
    @GetMapping("queryCarOwner")
    @Operation(summary = "根据车辆id查询绑定的住户数据")
    public Response<HouseholdDto> queryAllBy(
            @Parameter(description = "车辆id") @RequestParam Long id
    ) {
        //查询列表数据
        CarDto carDto = carService.selectById(id);
        if (carDto != null) {
            if (carDto.getVillageId() != null && StringUtils.isNotBlank(carDto.getOwnerMobile())) {
                HouseholdDto householdDto = householdService.selectByVillageIdAndMobile(carDto.getVillageId(), carDto.getOwnerMobile());
                if (householdDto != null) {
                    householdDto.setName(DesensitizedUtil.chineseName(householdDto.getName()));
                    householdDto.setMobile(DesensitizedUtil.mobilePhone(householdDto.getMobile()));
                    householdDto.setCardNo(DesensitizedUtil.idCardNum(householdDto.getCardNo(), 2, 2));
                    return Response.<HouseholdDto>ok().wrap(householdDto);
                }
            }
        }

        return Response.error("该车辆无绑定人员");
    }

    /**
     * 列表
     */
    @GetMapping("queryAllBy")
    @Operation(summary = "根据小区和手机号,查询手机号绑定的车辆列表")
    public Response<List<CarDto>> queryAllBy(
            @Parameter(description = "小区id") @RequestParam(required = false) Long villageId,
            @Parameter(description = "手机号") @RequestParam(required = false) String ownerMobile
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());
        List<CarDto> carDtos = carService.queryList(request.getParams());
        for (CarDto carDto : carDtos) {
            carDto.setLicense(DesensitizedUtil.carLicense(carDto.getLicense()));
        }
        return Response.<List<CarDto>>ok().wrap(carDtos);
    }

    /**
     * 列表
     */
    @GetMapping("queryCarsByHouseholdId")
    @Operation(summary = "根据住户id查询绑定的车辆列表")
    public Response<List<CarDto>> queryCarsByHouseholdId(
            @Parameter(description = "住户id") @RequestParam(required = false) Long householdId) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));
        super.fillAuthorityData(request.getParams());
        HouseholdDto householdDto = householdService.selectById(householdId);
        List<CarDto> carDtos = null;
        // 判断住户手机号是否为空
        if (StringUtils.isNotEmpty(householdDto.getMobile())) {
            request.getParams().put("villageId", householdDto.getVillageId());
            request.getParams().put("ownerMobile", householdDto.getMobile());
            carDtos = carService.queryList(request.getParams());
            for (CarDto carDto : carDtos) {
                carDto.setLicense(DesensitizedUtil.carLicense(carDto.getLicense()));
            }
        } else {
            carDtos = new ArrayList<>();
        }
        return Response.<List<CarDto>>ok().wrap(carDtos);
    }

    /**
     * 列表
     */
    @GetMapping("list")
    @RequirePermissions(values = "car:list")
    @Operation(summary = "车辆的分页查询列表")
    public Response<Page<CarDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());
        int total = carService.queryTotal(request.getParams());

        List<CarDto> list = null;
        if (total > 0) {
            list = carService.queryList(request.getParams());
            for (CarDto carDto : list) {
                carDto.setLicense(DesensitizedUtil.carLicense(carDto.getLicense()));
                carDto.setOwnerName(DesensitizedUtil.chineseName(carDto.getOwnerName()));
                carDto.setOwnerMobile(DesensitizedUtil.mobilePhone(carDto.getOwnerMobile()));
            }
        } else {
            list = new ArrayList<>();
        }

        Page<CarDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<CarDto>>ok().wrap(page);
    }

    /**
     * 编辑反显查询
     */
    @GetMapping("infoForEdit/{id}")
    @RequirePermissions(values = "car:edit")
    @Operation(summary = "查询单条车辆记录")
    public Response<CarDto> infoForEdit(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (carService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        CarDto carDto = carService.selectById(id);
        if (carDto.getRoomId()!=null){
            carDto.setRoom(villageRoomService.selectCacheById(carDto.getRoomId()));
        }
        return Response.<CarDto>ok().wrap(carDto);
    }

    /**
     * 根据车辆查询会员
     *
     * @param
     * @return
     */
    @GetMapping("info")
    @RequirePermissions(values = "parkingCardMember:info")
    @Operation(summary = "根据车辆查询会员")
    public Response<CarDto> info(
            @Parameter(description = "小区id", required = true) @RequestParam Long villageId,
            @Parameter(description = "车牌号", required = true) @RequestParam String license,
            @Parameter(description = "车牌颜色", required = true) @RequestParam Byte licenseColor
    ) {
        CarDto carDto = carService.selectOne(villageId, license, licenseColor);
        if (Objects.isNull(carDto)) {
            return Response.error("车辆未录入");
        }
        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(carDto.getId()));
        if (carService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        return Response.<CarDto>ok().wrap(carDto);
    }

    /**
     * 信息
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "car:info")
    @Operation(summary = "查询单条车辆记录")
    public Response<CarDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (carService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        CarDto carDto = carService.selectById(id);
        carDto.setLicense(DesensitizedUtil.carLicense(carDto.getLicense()));
        carDto.setOwnerName(DesensitizedUtil.chineseName(carDto.getOwnerName()));
        carDto.setOwnerMobile(DesensitizedUtil.mobilePhone(carDto.getOwnerMobile()));
        return Response.<CarDto>ok().wrap(carDto);
    }

    /**
     * 保存
     */
    @PostMapping("save")
    @RequirePermissions(values = "car:edit")
    @Operation(summary = "保存单条车辆记录")
    public Response<Object> save(@RequestBody @Validated CarDto carDto) {

        CarDto dvValue = carService.selectOne(carDto.getVillageId(), carDto.getLicense(), carDto.getLicenseColor());
        if (dvValue != null) {
            return Response.error("车辆已经存在");
        }
        //填充基础数据
        fillSaveCommonData(carDto);

        carService.save(carDto);

        return Response.ok();
    }

    /**
     * 修改
     */
    @PostMapping("update")
    @RequirePermissions(values = "car:edit")
    @Operation(summary = "修改单条车辆记录")
    public Response<Object> update(@RequestBody @Validated CarDto carDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(carDto.getId()));
        if (carService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        CarDto dvValue = carService.selectOne(carDto.getVillageId(), carDto.getLicense(), carDto.getLicenseColor());
        if (dvValue != null && !Objects.equals(carDto.getId(), dvValue.getId())) {
            return Response.error("车辆已经存在");
        }
        //填充基础数据
        fillEditCommonData(carDto);

        carService.updateById(carDto);

        return Response.ok();
    }

    /**
     * 删除
     */
    @PostMapping("delete")
    @RequirePermissions(values = "car:delete")
    @Operation(summary = "批量删除存在的车辆记录")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (carService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        carService.deleteBatch(ids);

        return Response.ok();
    }
}
